#include "StdAfx.h"
#include "Thread.h"
#include <PROCESS.H>

CThread::CThread(void)
{
	m_hThread = NULL;
	m_hEventThrdQuit = NULL;
	m_bExit = FALSE;
	m_socket = NULL;
	m_pThread = NULL;
}

CThread::~CThread(void)
{
}

void CThread::Start()
{
	DWORD dwThreadId = 0;
	m_bExit = FALSE;
	m_hThread = (HANDLE)::_beginthreadex(NULL, 0, thread, this, 0, NULL);
	m_hEventThrdQuit = CreateEvent(NULL, TRUE, FALSE, "ThreadQuit");
}

void CThread::Stop()
{
	if(m_hThread)
	{
		while (ResumeThread(m_hThread) > 0);
		m_bExit = TRUE;

		::SetEvent(m_hEventThrdQuit);
		Sleep(10);
		WaitForSingleObject(m_hThread, INFINITE);
		ReleaseMutex(m_hEventThrdQuit);
		CloseHandle(m_hEventThrdQuit);
		m_hEventThrdQuit = NULL;
		CloseHandle(m_hThread);
		m_hThread = NULL;
	}

	if(m_socket)
	{
		::closesocket(m_socket);
		m_socket = NULL;
	}

}

unsigned int __stdcall CThread::thread(void *pParam)
{
	CThread *pThread = (CThread*)pParam;
	
	while (WaitForSingleObject(pThread->m_hEventThrdQuit, 0) != WAIT_OBJECT_0)
	{
		if(pThread)
		{
			pThread->Run();
		}
	}

	return 0;
}
